//index.js
//获取应用实例
const app = getApp()
// 获取数据库数据
const db = wx.cloud.database()
import Toast from '../../vant/toast/toast';
Page({
  data: {
    showBackArrow: false,
    showLogo: false,
    tab: {
      activeTab: 0,
      color: '#333',
      width: 50
    },
    index: {
      indicatorDots: false,
      autoplay: true,
      interval: 3000,
      duration: 300,
      height: '100%'
    },
    indexData: {
      tabList: [{
        "title" : "首页",
        "grids" : [],
        "items" : []
      },
      {
        "title" : "新品推荐",
        "categoryId" : "004",
        "items" : []
      }]
    }
  },
  onLoad(options) {
    // 获取用户的openId
    app.globalData.openid = wx.getStorageSync('openId')
    // 获取首页数据
    db.collection('home_info')
    .orderBy('categoryId', 'desc')
    .get().then(res => {
      this.setData({
        'indexData': res.data[0],
        'tab.activeTab': 0
      })
      // 获取九宫格分类数据
      db.collection('goods_category').where({
        enable: 1
      })
      .get().then(res => {
        this.setData({
          'indexData.tabList[0].grids': res.data,
          'tab.activeTab': 0
        })
      })
    })
  },
  // 监听滚动事件
  onPageScroll(e) {
    let top = parseInt(e.scrollTop);
    if(top > 155) {
      this.setData({
        showLogo: true
      })
    } else {
      this.setData({
        showLogo: false
      })
    }
    if(top > 365) {
      this.setData({
        "tab.fixed": true
      })
    } else {
      this.setData({
        'activeTab': 0,
      })
    }
  },
  onTabChange(e) {
    // tab切换事件
    let index = e.detail.index
    let categoryId = this.data.indexData.tabList[index].categoryId
    // 获取分类数据
    if(index !== 0) {
      db.collection('goods_list').where({
        categoryId: categoryId,
        enable: 1
      })
      .get().then(res => {
        let param = {};
        let string = `indexData.tabList[${index}].items`
        param[string] = res.data
        this.setData(param)
      })
    }
  },
  handleTabChange(selectedId) {
    // selectId 表示被选中 tab 项的 id
    let sId = selectedId.detail;
    console.log("tab切换，" + sId + "被选中");
    switch(sId) {
      case '0':
        this.setData({
          showView: [true, false, false, false]
        })　　
        break;
      case '1':
        this.setData({
          showView: [false, true, false, false]
        })　　
        break;
      case '2':
        this.setData({
          showView: [false, false, true, false]
        })　　
        break;
      case '3':
        this.setData({
          showView: [false, false, false, true]
        })　　
        break;
    }
    // 将页面滑动到顶部
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300
    })
  }
})
